package cn.vic.db;

import cn.vic.config.TypeMapping;
import cn.vic.config.model.DatabaseElement;
import cn.vic.db.sql.BaseSqlInterface;
import cn.vic.db.sql.MysqlSqlFormat;
import cn.vic.db.sql.OracleSqlFormat;
import cn.vic.db.sql.SqlServerSqlFormat;
import cn.vic.enums.SqlDataBaseEnum;

import javax.management.RuntimeErrorException;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * 考虑 做成单例模式
 */
public class DatabaseFactory {

    private DatabaseFactory() {

    }

    /**
     * 创建 各种数据库table 对象
     *
     * @param connection
     * @param typeMapping
     * @return
     * @throws SQLException
     */
    public static Database createDatabase(Connection connection, TypeMapping typeMapping) throws SQLException {
        String dbProduct = connection.getMetaData().getDatabaseProductName();
        if (dbProduct.toLowerCase().contains("oracle")) {
            return new OracleDatabase(connection, typeMapping);
        } else if (dbProduct.toLowerCase().contains("sql server")) {
            return new SqlServerDatabase(connection, typeMapping);
        } else if (dbProduct.toLowerCase().contains("mysql")) {
            return new MySqlDatabase(connection, typeMapping);
        } else {
            return new DefaultDatabase(connection, typeMapping);
        }
    }

    /**
     * 获取 各种数据库修改Format
     *
     * @param databaseElement
     * @return
     */
    public static BaseSqlInterface getSqlFormat(DatabaseElement databaseElement) {
        SqlDataBaseEnum anEnum = databaseElement.getDataBaseEnum();
        if (anEnum.equals(SqlDataBaseEnum.ORACLE)) {
            return new OracleSqlFormat(databaseElement);
        } else if (anEnum.equals(SqlDataBaseEnum.SQLSERVER2000)) {
            return new SqlServerSqlFormat(databaseElement);
        } else if (anEnum.equals(SqlDataBaseEnum.SQLSERVER2005)) {
            return new SqlServerSqlFormat(databaseElement);
        } else if (anEnum.equals(SqlDataBaseEnum.JTDS)) {
            return new SqlServerSqlFormat(databaseElement);
        } else if (anEnum.equals(SqlDataBaseEnum.MYSQL)) {
            return new MysqlSqlFormat(databaseElement);
        }
        throw new RuntimeErrorException(new Error("SqlFormat 没有该数据库类型，需要添加或者扩展"));
    }


}
